What is @babel/types?
The @babel/types package is a part of the Babel compiler ecosystem. It contains methods for building and validating AST (Abstract Syntax Tree) nodes for JavaScript-like languages. It is commonly used for creating and transforming code within Babel plugins.
What are @babel/types's main functionalities?
AST Node Creation
This feature allows the creation of AST nodes. The code sample demonstrates how to create an identifier and a numeric literal using the package.
const t = require('@babel/types');
const identifier = t.identifier('myVariable');
const numericLiteral = t.numericLiteral(123);
AST Node Validation
This feature is used to validate if a node is of a specific type. The code sample checks if a node is an identifier.
const t = require('@babel/types');
const isValid = t.isIdentifier(t.identifier('myVariable'));
AST Node Transformation
This feature allows the transformation of AST nodes. The code sample creates a binary expression node that represents 'a + b'.
const t = require('@babel/types');
const binaryExpression = t.binaryExpression('+', t.identifier('a'), t.identifier('b'));
AST Node Traversal
This feature is not directly provided by @babel/types but is often used in conjunction with it. It involves traversing the AST and updating nodes. The code sample renames an identifier within the AST.
const t = require('@babel/types');
const traverse = require('@babel/traverse').default;
const ast = t.file(t.program([t.expressionStatement(t.identifier('myVariable'))]));
traverse(ast, {
enter(path) {
if (t.isIdentifier(path.node)) {
path.node.name = 'newVariable';
}
}
});
Other packages similar to @babel/types
acorn
Acorn is a small, fast, JavaScript-based JavaScript parser. It produces an abstract syntax tree similar to the one produced by @babel/types but does not include the same utilities for building or validating nodes.
esprima
Esprima is another JavaScript parser that produces an AST. It is used for static analysis and other code transformation tasks, similar to @babel/types, but it has its own API and does not provide the same helper functions for node creation and validation.
recast
Recast is a JavaScript AST manipulation library that uses Esprima under the hood. It provides a different set of utilities for parsing, transforming, and printing code, and it preserves source formatting, which is different from @babel/types.
@babel/types
Babel Types is a Lodash-esque utility library for AST nodes
See our website @babel/types for more information or the issues associated with this package.
Install
Using npm:
npm install --save-dev @babel/types
or using yarn:
yarn add @babel/types --dev